﻿using System;
using System.Collections.Generic;
using Cinemachine;
using UnityEngine;
using UnityEngine.AI;
using Yoozoo.Core.Extensions.Engine;
using Yoozoo.Framework.Core;
using Yoozoo.Managers.ResourceManagerV2.Framework;

namespace Gameplay.PVE.Survivor
{
    public class EnemyRandomSpawner
    {
        public RpgMissionEnemyRandomGroupConfig config;
        public float detectRadius;
        public float spawnRadius;
        public int densityCount;
        public List<BattleUnit> enemyList = new List<BattleUnit>();
        private int randomGroupWeightTotal;
        private int minDensityCount;
        private int maxDensityCount;
        private float increaseTime;
        private float startTime;
        
        private bool enabled = true;
        
        public void SetEnabled(bool value)
        {
            enabled = value;
        }
        
        public void Initialize(int count,float spawnRadius,float detectRadius,int groupId,int initCount = 0,float increaseTime = 0)
        {
            if (BattleDebug.enableLog)
            {
                BattleDebug.LogError("开始密度刷怪 " + groupId);
            }
    
            if (initCount == 0)
            {
                initCount = count;
            }

            enabled = true;
            minDensityCount = initCount;
            maxDensityCount = count;
            startTime = TimeManager.time;
            this.increaseTime = increaseTime;
            densityCount = initCount;
            this.spawnRadius = spawnRadius;
            this.detectRadius = detectRadius;
            config = BattleConfigManager.Instance.GetEnemyRandomGroupConfig(groupId);
            enemyList.Clear();
            randomGroupWeightTotal = 0;
            for (int i = 0; i < config.enemy_rand.Count; i++)
            {
                randomGroupWeightTotal += config.enemy_rand[i].y;
            }
        }

        public void Update()
        {
            var percent = (TimeManager.time - startTime) / increaseTime;
            percent = Mathf.Clamp01(percent);
            densityCount = (int)Mathf.Lerp(minDensityCount,maxDensityCount,percent);
            var teamGroupPosition = StageManager.Instance.TeamGroup.Position;
            var inRangeCount = 0;
            var spawnRadiusSqr = spawnRadius * spawnRadius;
            var detectRadiusSqr = detectRadius * detectRadius;
            for (int i = 0; i < enemyList.Count; i++)
            {
                var enemy = enemyList[i];
                var position = enemy.Position;
                var diff = position - teamGroupPosition;
                if (diff.sqrMagnitude > detectRadiusSqr)
                {
                    //RemoveEnemy(enemy);
                    //BattleDebug.LogError("超出区域，删除");
                    UnitManager.Instance.RemoveUnit(enemy);
                    i--;
                }
                else
                {
                    inRangeCount++;
                }
            }

            if (SurvivorManager.isTest)
            {
                TestManager.Instance.UpdateTestLabel("密度刷怪： ", inRangeCount + "/" + densityCount);
            }
            //BattleDebug.LogError("密度刷怪 " + inRangeCount + " " + densityCount);
            if (inRangeCount < densityCount)
            {
                //在边缘刷怪
                for (int i = 0; i < densityCount - inRangeCount; i++)
                {
                    var spawnPosition = StageManager.Instance.GetSpawnPoint();//BattleHelper.GetRandomPoint(spawnRadius,true);
                    var unit = UnitManager.Instance.CreateBattleUnit(2, GetEnemyId(),spawnPosition);
                    unit.InitAI(EEnemyAIType.SearchAllMap);
                    unit.SearchTarget();
                    unit.indexInSpawner = enemyList.Count;
                    enemyList.Add(unit);
                    //BattleDebug.Log("密度刷怪创建敌人 " + unit.unitId + " " + unit.indexInSpawner + " 与我的位置 " + Vector3.Distance(spawnPosition,teamGroupPosition));
                }
                /*var content = "";
                for (int i = 0; i < enemyList.Count; i++)
                {
                    var enemy = enemyList[i];
                    content += enemy.unitId + " " + enemy.indexInSpawner + " " + enemy.isDead + "\n";
                }
                BattleDebug.LogError("密度刷怪敌人列表 " + content);*/
            }
        }

        private int GetEnemyId()
        {
            var random = UnityEngine.Random.Range(0, randomGroupWeightTotal);
            var targetValue = 0;
            for (int i = 0; i < config.enemy_rand.Count; i++)
            {
                targetValue += config.enemy_rand[i].y;
                if (random < targetValue)
                {
                    return config.enemy_rand[i].x;
                }
            }
            return config.enemy_rand[config.enemy_rand.Count - 1].x;
        }
        
        public void RemoveEnemy(BattleUnit enemy)
        {
            var index = enemy.indexInSpawner;
            if (index >= 0)
            {
                //BattleDebug.LogError("密度刷怪移除敌人 " + enemy.unitId + " " + index);
                var lastIndex = enemyList.Count - 1;
                if (index < lastIndex)
                {
                    var last = enemyList[lastIndex];
                    last.indexInSpawner = index;
                    enemyList[index] = last;
                }
                enemyList.RemoveAt(lastIndex);
                enemy.indexInSpawner = -1;
            }
        }

        public void Stop()
        {
            if (BattleDebug.enableLog)
            {
                BattleDebug.Log("关闭密度刷怪");
            }
            for (int i = 0; i < enemyList.Count; i++)
            {
                enemyList[i].indexInSpawner = -1;
            }
            enemyList.Clear();
        }
    }
}
